package com.zhoug.fileselector3.looker.fragment;

import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.zhoug.common3.utils.LogUtils;
import com.zhoug.fileselector3.R;
import com.zhoug.fileselector3.looker.FileLookerActivity;
import com.zhoug.common3.imageloader.ZImageLoader;
import com.zhoug.player3.core.OnPlayListener;
import com.zhoug.player3.core.OnPlayProgressListener;
import com.zhoug.player3.core.ZPlayer;
import com.zhoug.player3.core.ui.VideoRatioTextureView;
import com.zhoug.player3.core.utils.Utils;
import com.zhoug.player3.exo.ExoPlayerHelper;


/**
 * 使用exoplayer框架播放视频
 */
public class VideoFragment extends BaseFileFragment {
    private static final String TAG = ">>>ExoVideoFragment";
    private VideoRatioTextureView mTextureView;
    private boolean play;
    private @ZPlayer.State int mPlayState;
    private ImageView mBtnPlay;
    private ImageView ivSlt;
    private RelativeLayout rlController;
    private SeekBar mSeekBar;
    private TextView tvPosition;
    private TextView tvDuration;
    private ProgressBar progressBar;
    private RelativeLayout clickView;


    private boolean uiIsShow = true;
    private Handler uiHandler = new Handler();//显示隐藏ui
    private boolean isSeekBarTouch;

    private ZPlayer mPlayer;

    @Override
    protected int getLayoutResId() {
        return R.layout.fileselector_fragment_video;
    }

    @Override
    protected void init(View root) {
        findViews(root);
        init();
    }


    private void findViews(View view) {
        mTextureView = view.findViewById(R.id.textureView);
        mBtnPlay = view.findViewById(R.id.iv_play);
        ivSlt = view.findViewById(R.id.iv_slt);
        rlController = view.findViewById(R.id.rl_controller);
        mSeekBar = view.findViewById(R.id.seekBar);
        tvPosition = view.findViewById(R.id.tv_position);
        tvDuration = view.findViewById(R.id.tv_duration);
        progressBar = view.findViewById(R.id.progressBar);
        clickView = view.findViewById(R.id.clickView);


        mBtnPlay.setOnClickListener(v -> {
            if (play) {
                mPlayer.pausePlay();
            } else {
                mPlayer.resumePlay();
            }
        });

        clickView.setOnClickListener(v -> {
            if (uiIsShow) {
                showUi(false);
            } else {
                showUi(true);
            }
        });
    }


    private void init() {
        if (zFile == null) {
            return;
        }
        //设置视频加载中的占位图片
        ZImageLoader.load(getContext(), ivSlt, zFile.getRealUrl(),null,null,null);
        initPlayer();
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//                updatePlayTime();
                tvPosition.setText(Utils.formatTime(progress * 1000));
//                LogUtils.d(TAG, "onProgressChanged: ");

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeekBarTouch = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isSeekBarTouch = false;
                if (mPlayer != null) {
                    mPlayer.seekTo(seekBar.getProgress() * 1000);
                }

                LogUtils.d(TAG, "onStopTrackingTouch: ");
            }
        });
    }


    private void setPlayButtonState(boolean play) {
        this.play = play;
        if (mBtnPlay != null) {
            if (play) {
                mBtnPlay.setImageResource(R.drawable.fileselector_icon_stop);
            } else {
                mBtnPlay.setImageResource(R.drawable.fileselector_icon_play);
            }
        }
    }

    /**
     * 初始化Player
     */
    private void initPlayer() {
        if (mPlayer == null) {
            mPlayer = new ExoPlayerHelper(getContext());
            mTextureView.setKeepScreenOn(true);
            mPlayer.setVideoTextureView(mTextureView);
            mPlayer.setMute(FileLookerActivity.VIDEO_MUTE);
            mPlayer.setRenderMode(ZPlayer.RENDER_MODE_ADJUST_RESOLUTION);
            mPlayer.setOnPlayListener(mPlayListener);
            mPlayer.setOnPlayProgressListener(new OnPlayProgressListener() {
                @Override
                public void onDurationChange(long duration) {
                    mSeekBar.setMax((int) (duration / 1000));
//                LogUtils.d(TAG, "onDurationChange:"+(int) (duration/1000));
                    tvDuration.setText(Utils.formatTime(duration));
                }

                @Override
                public void onPositionChange(long position) {
                    if (!isSeekBarTouch) {
                        mSeekBar.setProgress((int) (position / 1000));
//                LogUtils.d(TAG, "onPositionChange:"+(int) (position/1000));
                        tvPosition.setText(Utils.formatTime(position));
                    }

                }
            });
        }
        String url = zFile.getRealUrl();
        mPlayer.setPlayUrl(url);
    }


    private OnPlayListener mPlayListener = new OnPlayListener() {
        @Override
        public void onPlayStatusChange(@ZPlayer.State int state) {
            mPlayState = state;
            switch (state) {
                case ZPlayer.STATE_IDLE:
                    Log.d(TAG, "onPlayStatusChange:空闲");
                    showProgressBar(false);
                    setPlayButtonState(false);
                    break;
                case ZPlayer.STATE_START:
                    Log.d(TAG, "onPlayStatusChange:开始");
                    showProgressBar(true);
                    ivSlt.setVisibility(View.GONE);
                    setPlayButtonState(true);
                    break;
                case ZPlayer.STATE_PAUSE:
                    Log.d(TAG, "onPlayStatusChange:暂停");
                    showProgressBar(false);
                    setPlayButtonState(false);

                    break;
                case ZPlayer.STATE_PLAYING:
                    Log.d(TAG, "onPlayStatusChange:播放");
                    mPlayer.setMute(FileLookerActivity.VIDEO_MUTE);
                    ivSlt.setVisibility(View.GONE);
                    showProgressBar(false);
                    setPlayButtonState(true);
                    break;
                case ZPlayer.STATE_ENDED:
                    Log.d(TAG, "onPlayStatusChange:播放完成");
                    showProgressBar(false);
                    setPlayButtonState(false);
                    break;
            }

        }

        @Override
        public void onPlayError(int code, String error) {
            Log.e(TAG, error);
            toastLong(error);
            showProgressBar(false);
            setPlayButtonState(false);

        }

        /**
         * 视频宽高改变回掉
         *
         * @param width  视频宽
         * @param height 视频高
         */
        @Override
        public void onVideoSizeChanged(int width, int height) {

        }
    };


    /**
     * 释放资源
     */
    private void releasePlayer() {
        if (mPlayer != null) {
          /*  curPosition = mPlayer.getCurrentPosition();
            currentWindow = mPlayer.getCurrentWindowIndex();
            playWhenReady = mPlayer.getPlayWhenReady();*/
            mPlayer.release();
            mPlayer = null;
        }
        uiHandler.removeMessages(0);
    }

    private void play() {
        if (mPlayer != null) {
            //播放完了重新开始
            if (mPlayState == ZPlayer.STATE_ENDED) {
                mPlayer.seekTo(0);
                mSeekBar.setProgress(0);
            }
            mPlayer.resumePlay();

        }
    }

    private void pause() {
        if (mPlayer != null) {
            mPlayer.pausePlay();
            setPlayButtonState(false);
        }
    }


    private void showProgressBar(boolean show) {
        if (show && progressBar.getVisibility() != View.VISIBLE) {
            progressBar.setVisibility(View.VISIBLE);
        } else if (!show && progressBar.getVisibility() != View.GONE) {
            progressBar.setVisibility(View.GONE);
        }
    }






    /**
     * 显示ui
     *
     * @param show
     */
    private void showUi(boolean show) {
        if (uiIsShow == show || rlController == null) return;
        if (show) {
            rlController.setVisibility(View.VISIBLE);
            uiIsShow = true;
            //2秒后自动隐藏ui
            uiHandler.removeMessages(0);//默认任务的what为0
            uiHandler.postDelayed(() -> showUi(false), 3000);
        } else {
            rlController.setVisibility(View.GONE);
            uiIsShow = false;

        }
    }


    /**
     * 视图是否已经对用户可见，系统的方法
     *
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        LogUtils.d(TAG, "setUserVisibleHint: isVisibleToUser=" + isVisibleToUser);
        if (isResumed()) {
            if (isVisibleToUser) {
                play();
            } else {
                pause();
            }
        }

        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.d(TAG, "onResume: " + this.getClass().getName());
        boolean userVisibleHint = getUserVisibleHint();
        if (userVisibleHint) {
            play();
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        LogUtils.d(TAG, "onPause: ");
        pause();
    }

    @Override
    public void onDestroyView() {
        LogUtils.d(TAG, "onDestroyView: ");
        super.onDestroyView();
//        release();
        releasePlayer();

    }


}
